import store from "@/store"
import router from "@/router"
let that
export default class scroll {
   constructor(){
     this.timer = null
     this.beforeTop  = 0
     this.RecommendArticleInfo=store.state.Home.RecommendArticleInfo //推荐的博客信息
     this.ArticleDetailCatalog=store.state.ArticleDetail.ArticleDetailCatalog //文章详情目录
     that = this
   }
   // 导航
   Navigation(scrollTop){
      // 下滚
      if(this.beforeTop < scrollTop ){
         store.commit('Tool/SETNAVIGATION',[false,false])
      }
      //上滚
      else if(this.beforeTop >= scrollTop ) {
            if(this.beforeTop > 100)
            store.commit('Tool/SETNAVIGATION',[true,true])
            else  store.commit('Tool/SETNAVIGATION',[true,false])
      }
   }
   // 主页
   Home(scrollTop, clientHeight, scrollHeight){
      if (scrollTop + clientHeight === scrollHeight){
         if(this.RecommendArticleInfo.length < this.RecommendArticleInfo.total){
            store.dispatch('Home/GetRecommendArticle')
         }
      }
   
   }
   // 详情
   ArticeDetail(scrollTop){
      let ArticleDetailCatalog = store.state.ArticleDetail.ArticleDetailCatalog
      let id = 0
      for(let i =0 ; i< ArticleDetailCatalog.length ;i+=1){
         if(scrollTop<ArticleDetailCatalog[i].top){
            id =i
            break
         }
         if(i< ArticleDetailCatalog.length -1 )
         {
            if(scrollTop>=ArticleDetailCatalog[i].top && scrollTop<ArticleDetailCatalog[i+1].top) 
            {
               id =i
               break
            }
         }  
        else id = i
      }
      store.commit('ArticleDetail/SETCATALOGNOWID',id)
   }
   scroll_JL(){
    

     if (this.timer != null) return
     this.timer =setTimeout(() => {
        this.scroll_()
        clearTimeout(this.timer)
        this.timer = null
     }, 50);
   }
    scroll_ (){
        // document.scrollingElement
         let scroll =  document.scrollingElement ||  document.documentElement ||  document.body
         const {scrollTop, clientHeight, scrollHeight} = scroll
         
         //导航条
         this.Navigation(scrollTop)
  
         //主页
          if(router.currentRoute.name=='home' || router.currentRoute.name == null)
          this.Home(scrollTop, clientHeight, scrollHeight)
         //详情
         else if(router.currentRoute.name=='articleDetail' )
         this.ArticeDetail(scrollTop)

          this.beforeTop=scrollTop
    }
    
    star(){
        window.addEventListener('scroll',this.scroll_JL.bind(that));
    }
}




    

